package org.pp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.pp.admin.dto.PpUserStatusSwitch;
import org.pp.core.*;
import org.pp.dto.PageDto;
import org.pp.entity.PpGoods;
import org.pp.entity.PpUser;
import org.pp.entity.PpUserCollect;
import org.pp.entity.SysUser;
import org.pp.mapper.PpUserMapper;
import org.pp.miniapp.dto.UserInfoUpdate;
import org.pp.service.IPpGoodsService;
import org.pp.service.IPpGoodsSkuService;
import org.pp.service.IPpUserCollectService;
import org.pp.service.IPpUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.pp.store.OssStore;
import org.pp.util.JwtUtil;
import org.pp.util.PageUtil;
import org.pp.vo.MiniappGoodsVo;
import org.pp.vo.MiniappLoginVo;
import org.pp.vo.MiniappUserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author haima
 * @since 2024-10-01
 */
@Service
@Slf4j
public class PpUserServiceImpl extends ServiceImpl<PpUserMapper, PpUser> implements IPpUserService {

    @Value("${wx.appid}")
    private String appid;
    @Value(("${wx.secret}"))
    private String secret;

    @Autowired
    IPpUserCollectService collectService;

    @Autowired
    IPpGoodsService goodsService;

    @Autowired
    OssStore ossStore;

    @Setter
    @Getter
    static class WxResultBean{
        String openid;
        int errcode;
        String errmsg;
    }

    @Override
    public MiniappLoginVo login(String code) {
        String url="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> param= new ConcurrentHashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        param.put("grant_type","authorization_code");
        param.put("js_code",code);

        String body = HttpUtil.get(url, param);
        log.info("微信返回："+body);
        WxResultBean bean = JSONUtil.toBean(body, WxResultBean.class);
        if(StrUtil.isBlank(bean.getOpenid())){
            //
            throw BizExcept.erro("微信授权失败");
        }else{
            PpUser one = getOne(new LambdaQueryWrapper<PpUser>().eq(PpUser::getOpenId, bean.getOpenid()));
            if(one==null){
                PpUser user= new PpUser();
                user.setOpenId(bean.getOpenid());
                save(user);
                one=user;
            }
            String jwtToken = JwtUtil.createJwtToken(Map.of(MiniappConstants.jwtLoginKey, one.getUserId()),
                    MiniappConstants.jwtExpireUnit, MiniappConstants.jwtExpireTime);
            MiniappLoginVo vo= new MiniappLoginVo();
            vo.setUserId(one.getUserId());
            vo.setAvatar(ossStore.getUrl(one.getAvatar()));
            vo.setNickName(one.getNickName());
            vo.setToken(jwtToken);
            return vo;
        }
    }

    @Override
    public MiniappUserInfoVo infoUpdate(UserInfoUpdate dto) {
        Long userId = MiniappSessionUtil.getUserId();
        PpUser editeUser= new PpUser();
        editeUser.setUserId(userId);
        editeUser.setAvatar(dto.getAvatar());
        editeUser.setNickName(dto.getNickName());
        updateById(editeUser);
        MiniappUserInfoVo vo = BeanUtil.copyProperties(editeUser, MiniappUserInfoVo.class);
        vo.setAvatarUrl(ossStore.getUrl(vo.getAvatar()));
        return vo;
    }

    @Override
    public MiniappUserInfoVo info() {
        PpUser user = getById(MiniappSessionUtil.getUserId());
        Assertion.nullThrow(user,"用户不存在");
        MiniappUserInfoVo vo = BeanUtil.copyProperties(user, MiniappUserInfoVo.class);
        vo.setAvatarUrl(ossStore.getUrl(vo.getAvatar()));
        return vo;
    }

    @Override
    public Boolean collect(Long goodsId) {
        Long userId = MiniappSessionUtil.getUserId();
        PpUserCollect one = collectService.getOne(new LambdaQueryWrapper<PpUserCollect>()
                .eq(PpUserCollect::getUserId, userId)
                .eq(PpUserCollect::getGoodsId, goodsId)
        );
        if(Objects.isNull(one)){
            PpUserCollect collect= new PpUserCollect();
            collect.setUserId(userId);
            collect.setGoodsId(goodsId);
            collect.setStatus(true);
            collectService.save(collect);
            return true;
        }else{
            PpUserCollect edit= new PpUserCollect();
            edit.setCollectId(one.getCollectId());
            edit.setUserId(userId);
            edit.setGoodsId(goodsId);
            edit.setStatus(!one.getStatus());
            collectService.updateById(edit);
            return !one.getStatus();
        }
    }

    @Override
    public Boolean getCollect(Long goodsId) {
        Long userId = MiniappSessionUtil.getUserId(false);
        if(Objects.isNull(userId)){
            return false;
        }
        PpUserCollect one = collectService.getOne(new LambdaQueryWrapper<PpUserCollect>()
                .eq(PpUserCollect::getUserId, userId)
                .eq(PpUserCollect::getGoodsId, goodsId)
        );

        return Objects.nonNull(one)&& one.getStatus();
    }

    @Override
    public PageBean<MiniappGoodsVo> getCollectPageList(PageDto dto) {
        Long userId = MiniappSessionUtil.getUserId();
        if(dto.isPageShow()){
            PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        }
        List<PpUserCollect> list = collectService.list(new LambdaQueryWrapper<PpUserCollect>()
                .eq(PpUserCollect::getUserId, userId));

        PageInfo<PpUserCollect> pageInfo = new PageInfo<>(list);

        List<PpGoods> ppGoods = goodsService.listByIds(list.stream().map(e -> e.getGoodsId()).toList());
        PageBean<MiniappGoodsVo> res= new PageBean<>();
        ppGoods.forEach(e->e.setCover(ossStore.getUrl(e.getCover())));
        res.setTotal(pageInfo.getTotal());
        res.setList(BeanUtil.copyToList(ppGoods, MiniappGoodsVo.class));
        res.setPages(pageInfo.getPages());
        res.setPageNum(pageInfo.getPageNum());
        res.setPageSize(pageInfo.getPageSize());
        return res;
    }

    @Override
    public void statusSwitch(PpUserStatusSwitch dto) {
        PpUser user = getById(dto.getUserId());
        Assertion.nullThrow(user,"用户不存在");
        PpUser editeUser = new PpUser();
        editeUser.setUserId(dto.getUserId());
        editeUser.setStatus(MiniappConstants.statusActive.equals(user.getStatus()) ?
                MiniappConstants.statusDisabled : MiniappConstants.statusActive);

        updateById(editeUser);
    }

}
